
/**
 * 日期时间格式化
 *
 * @export
 * @param {string} [format] default: yyyy-MM-dd HH:mm:ss
 * @param {Date}   [date]   default: new Date()
 * @returns
 */

export default function moment (date, format) {
  const relFormat = format || 'yyyy-MM-dd HH:mm:ss'
  const relDate = date ? new Date(date) : new Date()
  function show12Hours (hours) {
    if (hours === 24) return '00'
    if (hours > 12) return `${hours < 22 ? '0' : ''}${hours - 12}`
    return `${hours < 10 ? '0' : ''}${hours}`
  }
  const formatter = relFormat
    .replace(/(yyyy|YYYY)/g, relDate.getFullYear())
    .replace(/MM/g, `${relDate.getMonth() < 9 ? '0' : ''}${relDate.getMonth() + 1}`)
    .replace(/(dd|DD)/g, `${relDate.getDate() < 10 ? '0' : ''}${relDate.getDate()}`)
    .replace(/HH/g, `${relDate.getHours() < 10 ? '0' : ''}${relDate.getHours()}`)
    .replace(/hh/g, show12Hours(relDate.getHours()))
    .replace(/mm/g, `${relDate.getMinutes() < 10 ? '0' : ''}${relDate.getMinutes()}`)
    .replace(/ss/g, `${relDate.getSeconds() < 10 ? '0' : ''}${relDate.getSeconds()}`)
  return formatter
}
